#Author: Tanyong
# *-* coding:utf8 *-*
# @time       : 2018/7/17 20:00
# @Author     : Tanyong
# @Site       : 
# @File       : __init__.py.py
# @Software   : PyCharm
import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask import current_app
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from flask_wtf.csrf import generate_csrf
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf import CSRFProtect
from flask_session import Session
from config import config
from info.utils.common import user_login_data

db = SQLAlchemy()
redis_store = None

def setup_log(config_name):
    """配置日志"""

    # 设置日志的记录等级
    logging.basicConfig(level=config[config_name].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    # 日志配置, 通过传入一个配置名字, 来指定日志的配置
    setup_log(config_name)
    # 加载配置
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # 使用db.init_app()来配置数据库
    db.init_app(app)
    # 创建redis存储空间
    global redis_store
    redis_store = StrictRedis(config[config_name].REDIS_HOST, config[config_name].REDIS_PORT, decode_responses=True)
    # CSRFProtect保护开启
    CSRFProtect(app)
    # 指定Session存储位置
    Session(app)
    # 添加模板过滤器
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, "index_class")

    # 设置 csrf_token
    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 整体程序的404页面
    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        user = g.user
        data = {"user": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    # 增加一个请求钩子, 让管理不能访问非 admin的页面
    @app.before_request
    def not_admin():
        is_admin = session.get('is_admin', False)
        if is_admin and request.url.find("admin") == -1:
            return redirect(url_for('admin.index'))

    # # 使用请求钩子实现 装饰器的功能
    # from info.models import User
    # @app.before_request
    # def before_request():
    #     user_id = session.get('user_id')
    #     user = None
    #     if user_id:
    #         try:
    #             user = User.query.get(user_id)
    #         except Exception as e:
    #             current_app.logger.error(e)
    #
    #     g.user = user


    # 注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu, url_prefix="/admin")

    return app